package com.edushare.common.dao;

import java.util.ArrayList;
import java.util.List;

import com.edushare.common.orm.ORMInterface;
import com.edushare.common.vo.CourseDeptLink;
import com.edushare.common.vo.Courses;
import com.edushare.common.vo.Departments;

public class CourseDeptLinkDAO extends CayenneBasedDAO {

	public CourseDeptLinkDAO(ORMInterface ormInterface) {
		super(ormInterface);
	}

	public void moveCourseToDept(Courses c, Departments dept) {
		List<CourseDeptLink> cdlList = c.getDeptLinks();
		getDataContext().deleteObjects(cdlList);
		createCourseDeptLink(CourseDeptLink.DEPT_COURSE_OWNER, c, dept);
	}
	
	public void removeCourseFromDept(Courses c, Departments dept){
		List<CourseDeptLink> cdlList = c.getDeptLinks();
		CourseDeptLink cdlDelete = null;
		for(CourseDeptLink cdl:cdlList){
			if(cdl.getDepartment() == dept){
				cdlDelete = cdl;
			}
		}
		if(cdlDelete != null){
			deleteCourseDeptLink(cdlDelete);
		}
	}

	public void createCourseDeptLink(int courseDeptLinkType, Courses c,
			Departments dept) {
		CourseDeptLink courseDeptLink = getDataContext().newObject(
				CourseDeptLink.class);
		courseDeptLink.setCourse(c);
		courseDeptLink.setDepartment(dept);
		courseDeptLink.setCourseDeptAssnType(courseDeptLinkType);

		getDataContext().commitChanges();
	}

	public void deleteCourseDeptLink(CourseDeptLink link) {
		getDataContext().deleteObject(link);
	}

	public List<Courses> getAllCourses(Departments dept) {
		List<CourseDeptLink> cdlList = dept.getCourseLinks();
		List<Courses> course = new ArrayList<Courses>();
		for (CourseDeptLink cdl : cdlList) {
			course.add(cdl.getCourse());
		}
		return course;
	}

	public List<Courses> getOwnedCourses(Departments dept) {
		List<CourseDeptLink> cdlList = dept.getCourseLinks();
		List<Courses> course = new ArrayList<Courses>();
		for (CourseDeptLink cdl : cdlList) {
			if (cdl.getCourseDeptAssnType() == CourseDeptLink.DEPT_COURSE_OWNER)
				course.add(cdl.getCourse());
		}
		return course;
	}

	public List<Courses> getSubscribedCourses(Departments dept) {
		List<CourseDeptLink> cdlList = dept.getCourseLinks();
		List<Courses> course = new ArrayList<Courses>();
		for (CourseDeptLink cdl : cdlList) {
			if (cdl.getCourseDeptAssnType() == CourseDeptLink.DEPT_COURSE_SUBSCRIBER)
				course.add(cdl.getCourse());
		}
		return course;
	}

}
